<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>后台管理</title>
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/static/admin/css/common.css"/>
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/static/admin/css/main.css"/>
    <script type="text/javascript" src="__PUBLIC__/static/admin/js/libs/modernizr.min.js"></script>
</head>
<body>
{include file="Public/top" /}
<div class="container clearfix">
    {include file="Public/left" /}
    <!--/sidebar-->
    <div class="main-wrap">

        <div class="crumb-wrap">
            <div class="crumb-list"><i class="icon-font"></i><a href="{:url('admin/index/index')}">首页</a><span
                    class="crumb-step">&gt;</span><a class="crumb-name"
                                                     href="{:url('admin/cate/list')}">问卷管理</a><span
                    class="crumb-step">&gt;</span><span>修改问卷</span></div>
        </div>
        <div class="result-wrap">
            <div class="result-content">
                <form action="" method="post" id="myform" name="myform" enctype="multipart/form-data">
                    <input type="hidden" name="id" value="{$cates.id}">
                    <table class="insert-tab" width="100%">
                        <tbody>
                        <tr>
                            <th width="10%"><i class="require-red">*</i>问卷名称：</th>
                            <td>
                                <input class="common-text required" id="catename" name="catename" size="50"
                                       value="{$cates.catename}" type="text">
                            </td>
                        </tr>
                        <tr>
                            <th>


                                问卷描述：





                                <!-- 文件输入元素，隐藏起来 -->
                                <input type="file" id="fileInput" style="display: none;" accept="image/*">
                            </th>
                            <td><textarea name="desc" class="common-textarea" id="desc"   cols="30" style="width: 50%;"
                                          rows="2">{$cates.desc}</textarea></td>
                        </tr>
                        <script>
                            // 图片上传处理函数
                            function uploadImage(imgId) {
                                // 获取文件输入元素
                                var fileInput = document.getElementById('fileInput');
                                // 触发文件输入元素的点击事件
                                fileInput.click();

                                // 当文件输入值改变时（即用户选择了文件），处理文件上传
                                fileInput.onchange = function () {
                                    var file = this.files[0]; // 获取选择的文件
                                    if (file) {
                                        // 在这里实现图片上传逻辑，例如使用 FormData 和 AJAX 发送到服务器
                                        console.log('文件已选择：', file);
                                        console.log('文件de名：', imgId);
                                        // 上传文件的代码应该放在这里,传入对应题目显示的ID
                                        uploadImage_second(file,imgId);
                                    }


                                    // 获取到图片名称和路径

                                    // 显示在对应位置 ，即imgId

                                    // 获取 img 元素

                                    // var imgElement = document.getElementById(imgId+'-img');
                                    var imgElement = document.getElementById(imgId + '-img');
                                    // 设置 img 的 src 属性为 22.jpg
                                    // imgElement.src = '__PUBLIC__/static/admin/images/' + imgId + '.gif';

                                    // 更改掉input里面的内容
                                    // const inputToImgElement = document.getElementById(imgId);
                                    // imgElement.src = '__PUBLIC__/static/admin/images/' + imgId + '.gif';
                                    // inputToImgElement.value = '<img src= ' + imgElement.src + '>';
                                    // 隐藏掉input里面的内容-

                                    // 清空fileInput的内容
                                    fileInput.value = '';

                                };
                            }

                            function uploadImage_second(file,imgId) {
                                const input = document.getElementById('imageUpload');
                                // const file = input.files[0]; test git
                                const formData = new FormData();
                                formData.append('image', file);

                                fetch('__PUBLIC__/index.php/index/article/upload_api', {
                                    method: 'POST',
                                    body: formData
                                })
                                    .then(response => response.text()) // 假设API返回的是JSON格式的数据
                                    .then(data => {

                                        // 创建一个Date对象，表示当前日期和时间
                                        const now = new Date();

                                        // 获取年份，并转为字符串，确保是4位数（例如 "2023"）
                                        const year = now.getFullYear().toString().padStart(4, '0');

                                        // 获取月份，并转为字符串，确保是2位数（例如 "09" 表示9月）
                                        const month = (now.getMonth() + 1).toString().padStart(2, '0');

                                        // 获取日期，并转为字符串，确保是2位数（例如 "25" 表示25日）
                                        const day = now.getDate().toString().padStart(2, '0');

                                        // 将年、月、日拼接成一个8位数的字符串（例如 "20230925"）
                                        const formattedDate = year + month + day;

                                        console.log(formattedDate); // 输出类似 "20230925" 的字符串



                                        data = data.replace(/^\uFEFF/, '');
                                        // 假设API返回的数据中有一个'imageUrl'字段，包含了上传图片的URL
                                        const imageUrl = '__PUBLIC__/static/uploads/'+formattedDate+'/'+data;
                                        console.log(data);
                                        console.log(imageUrl);
                                        const displayImage = document.getElementById(imgId+'-img');
                                        displayImage.src = imageUrl;
                                        displayImage.style.display = "block";

                                        // 追加input里面的内容
                                        const inputToImgElement = document.getElementById(imgId);
                                        inputToImgElement.value = getContentBeforeImgTag(inputToImgElement.value)  + '<br> <img src=' + imageUrl + ' width=300px height=300px> <br>';

                                        // 隐藏掉input里面的内容-
                                    })
                                    .catch(error => {
                                        console.error('上传图片时出错:', error);
                                    });
                            }
                            function getContentBeforeImgTag(str) {
                                const imgIndex = str.indexOf('<br');
                                if (imgIndex !== -1) {
                                    return str.substring(0, imgIndex);
                                } else {
                                    return str; // 或者可以返回一个空字符串，取决于你想要如何处理不包含"<img"的情况
                                }
                            }
                            function uploadImageApi(file,) {
                                // const input = document.getElementById('imageUpload');
                                // const file = input.files[0];

                                if (file) {
                                    const formData = new FormData();
                                    formData.append('image', file);

                                    fetch('__PUBLIC__/index.php/index/article/upload_api', {
                                        method: 'POST',
                                        body: formData
                                    })
                                        .then(response => response.text()) // 假设API返回的是JSON格式数据
                                        .then(data => {
                                            console.log(data);
                                            data = data.replace(/^\uFEFF/, '');
                                            if (data.success) {
                                                // 假设API返回的数据中有一个'url'字段，包含了返回的图片的URL
                                                // const returnedImageUrl = data.url;
                                                const imageUrl = '__PUBLIC__/static/uploads/20240302/'+data;
                                                document.getElementById('returnedImage').src = returnedImageUrl;
                                                console.error('上传成功:', data.success);
                                            } else {
                                                console.error('上传1失败:', data.error);
                                            }
                                        })
                                        .catch(error => {
                                            console.error('上传2失败:', error);
                                        });
                                } else {
                                    console.error('未选择文件');
                                }
                            }

                            // 图片上传函数
                            async function uploadImage_new(file) {
                                const formData = new FormData();
                                formData.append('image', file);

                                try {
                                    const response = await fetch('__PUBLIC__/index.php/index/article/upload_api', {
                                        method: 'POST',
                                        body: formData
                                    });

                                    if (!response.ok) {
                                        throw new Error('Network response was not ok');
                                    }

                                    const data = await response.json();
                                    handleApiResponse(data);

                                } catch (error) {
                                    console.error('There was a problem with your fetch operation:', error);
                                }
                            }

                            // 处理API响应的函数
                            function handleApiResponse(data) {
                                const imagePreview = document.getElementById('imagePreview');
                                const errorMessage = document.getElementById('errorMessage');

                                if (data.code === 200) {
                                    // 假设你的API接口返回的数据结构中包含一个图片的URL
                                    const imageUrl = data.imageUrl;
                                    imagePreview.innerHTML = `<img src="${imageUrl}" alt="Uploaded Image">`;
                                    errorMessage.textContent = ''; // 清空错误信息
                                } else if (data.code === 400) {
                                    errorMessage.textContent = '接口图片上传失败';
                                    imagePreview.innerHTML = ''; // 清空图片预览
                                }
                            }
                        </script>


                        {volist name="cate_contens" id="vo"}

                        <tr id="w1">
                            <th>问题{$i}：</th>
                            <td>
                                <p>问题标题</p><input class="common-text" name="title{$i}" size="50" value="{$vo.title}"
                                                      type="text"> 分数：<input class="common-text" name="score{$i}"
                                                                               size="5" value="{$vo.score}"
                                                                               type="text">
                                <p>问题类型：

                                    <input name="type{$i}" value="0" type="radio" {if condition="$vo.type eq 0 " }
                                           checked="" {/if} > 单选题
                                    <input name="type{$i}" value="1" type="radio" {if condition="$vo.type eq  1 " }
                                           checked="" {/if} > 多选题

                                </p>
                                <input type="hidden" name="id{$i}" value="{$vo.id}">


                                <p>选项1：<input class="common-text" id="answer1{$i}" name="answer1{$i}" size="50"
                                                 value="{$vo.answer1}"
                                                 type="text">



                                    <img onclick="uploadImage('answer1{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png"> 答案：<input type="checkbox"
                                                                                                   name="correct1{$i}"
                                                                                                   {if
                                                                                                   condition="$vo.correct1 eq  1 "
                                                                                                   }
                                                                                                   checked="" {/if}
                                    >
                                    <div><img id="answer1{$i}-img" src="" alt="" width="300px" height="300px"  style="display: none"></div>
                                </p>
                                <p>选项2：<input class="common-text" id="answer2{$i}" name="answer2{$i}" size="50"
                                                value="{$vo.answer2}"
                                                type="text">

                                    <img onclick="uploadImage('answer2{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png">
                                    答案：<input type="checkbox" name="correct2{$i}"  {if condition="$vo.correct2 eq  1 " }
                                                checked="" {/if}>
                                <div> <img id="answer2{$i}-img" src="" alt="" width="300px" height="300px"  style="display: none"></div>
                                </p>
                                <p>选项3：<input class="common-text" id="answer3{$i}" name="answer3{$i}" size="50"
                                                value="{$vo.answer3}"
                                                type="text">
                                    <img onclick="uploadImage('answer3{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png">
                                    答案：<input type="checkbox" name="correct3{$i}"  {if condition="$vo.correct3 eq  1 " }
                                                checked="" {/if}>
                                <div><img id="answer3{$i}-img" src="" alt="" width="300px" height="300px"  style="display: none"></div>
                                </p>
                                <p>选项4：<input class="common-text" id="answer4{$i}" name="answer4{$i}" size="50"
                                                value="{$vo.answer4}"
                                                type="text">
                                    <img onclick="uploadImage('answer4{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png">
                                    答案：<input type="checkbox" name="correct4{$i}"  {if condition="$vo.correct4 eq  1 " }
                                                checked="" {/if}>
                                <div><img id="answer4{$i}-img" src="" alt=""  width="300px" height="300px"  style="display: none"></div>
                                </p>
                                <p>选项5：<input class="common-text" id="answer5{$i}" name="answer5{$i}" size="50"
                                                value="{$vo.answer5}"
                                                type="text">
                                    <img onclick="uploadImage('answer5{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png">
                                    答案：<input type="checkbox" name="correct5{$i}"  {if condition="$vo.correct5 eq  1 " }
                                                checked="" {/if}>
                                <div><img id="answer5{$i}-img" src="" alt=""  width="300px" height="300px"  style="display: none"></div>
                                </p>
                                <p>选项6：<input class="common-text" id="answer6{$i}" name="answer6{$i}" size="50"
                                                value="{$vo.answer6}"
                                                type="text">
                                    <img onclick="uploadImage('answer6{$i}')"
                                         src="__PUBLIC__/static/admin/images/img.png">
                                    答案：<input type="checkbox" name="correct6{$i}"  {if condition="$vo.correct6 eq  1 " }
                                                checked="" {/if}>
                                <div><img id="answer6{$i}-img" src="" alt=""  width="300px" height="300px" style="display: none"></div>
                                </p>
                        </tr>
                        {/volist}
                        <tr>

                            <th></th>
                            <td>
                                <input class="btn btn-primary btn6 mr10" value="提交" type="submit">
                                <input class="btn btn6" onclick="history.go(-1)" value="返回" type="button">
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </form>
            </div>
        </div>

    </div>
    <!--/main-->
</div>
</body>
</html>